package com.fa4j.code.generate.controller;

import com.fa4j.code.generate.model.CodeGenerateCmd;
import com.fa4j.code.generate.model.CodeGenerateFile;
import com.fa4j.code.generate.service.CodeGenerateService;
import com.fa4j.common.web.annotation.ApiMethod;
import com.fa4j.common.web.model.AppType;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成结果 Web接口
 *
 * @since 2025-09-16 10:21:44
 */
@RestController
@RequestMapping("code/generate")
@RequiredArgsConstructor
public class CodeGenerateController {

    private final CodeGenerateService codeGenerateService;

    @PostMapping
    @ApiMethod(name = "代码生成-生成", type = AppType.MANAGE)
    public void generate(@RequestBody @Valid CodeGenerateCmd cmd, HttpServletResponse response) throws IOException {
        List<CodeGenerateFile> fileList = codeGenerateService.generate(cmd);
        String fileName = URLEncoder.encode(cmd.getProjectName() + ".zip", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        OutputStream out = response.getOutputStream();
        try (ZipOutputStream zos = new ZipOutputStream(out)) {
            for (CodeGenerateFile generateFile : fileList) {
                ZipEntry zipEntry = new ZipEntry(generateFile.getFilePath() + generateFile.getFileName());
                zos.putNextEntry(zipEntry);
                zos.write(generateFile.getContent().getBytes(StandardCharsets.UTF_8));
                zos.closeEntry();
            }
        }
        out.flush();
    }


}
